﻿using Net.Sz.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 * 
 * @author 失足程序员
 * @Blog http://www.cnblogs.com/shizuchengxuyuan/
 * @mail 492794628@qq.com
 * @phone 13882122019
 * 
 */
namespace Net.Sz.Framework.Util
{

    /// <summary>
    /// 每秒钟能产生 1000万 个id
    /// <para>分10组（0-9），分别计算id,</para>
    /// <para>启动程序后，重复周期是 10 年,</para>
    /// <para>上一次启动和下一次启动之间重启周期是 1 秒钟</para>
    /// 
    /// <para>PS:</para>
    /// <para>@author 失足程序员</para>
    /// <para>@Blog http://www.cnblogs.com/shizuchengxuyuan/</para>
    /// <para>@mail 492794628@qq.com</para>
    /// <para>@phone 13882122019</para>
    /// </summary>
    public class LongId1 : LongId0
    {

        /// <summary>
        /// 
        /// </summary>
        protected int CONSTID = 1;

        protected LongId1() { }

        /// <summary>
        /// 每秒钟能产生 1000万 个id
        /// <para>分10组（0-9），分别计算id,</para>
        /// <para>启动程序后，重复周期是 10 年,</para>
        /// <para>上一次启动和下一次启动之间重启周期是 1 秒钟</para>
        /// </summary>
        /// <param name="idd">0~9</param>
        public LongId1(int idd)
        {
            if (0 > idd || 9 < idd)
            {
                throw new Exception("idd 0~9");
            }
            this.MAXID = 99999999;
            this.MAXHEAD = 10000000;
            CONSTID = idd;
        }

        /// <summary>
        /// 年月日时分服务器id和自增id组合的19位id
        /// </summary>
        /// <returns></returns>
        public virtual Int64 GetId()
        {
            long now = TimeUtil.CurrentTimeMillis() / 1000;
            long tmpid = 0;
            lock (this)
            {
                if (now != upTime)
                {
                    upTime = now;
                    /*相对耗时*/
                    string datekey = DateTime.Now.ToString("yyyyMMddHHmmss").Substring(3);
                    this.idHead = Convert.ToInt64(datekey + CONSTID.ToString()) * this.MAXHEAD;
                    id = -1;
                }
                ++id;
                if (id > this.MAXID)
                {
                    throw new Exception("超过每秒钟创建量 " + this.MAXID);
                }
                tmpid = this.idHead + id;
            }
            return tmpid;
        }
    }
}
